package com.dtdream.emr;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class RegexpInstr extends UDF {

    public int evaluate(String source, String pattern) {
        if (null == source || null == pattern){
            return 0;
        }
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(source);
        int ret = -1;
        if (m.find()) {
            ret = m.start();
        }
        return ret;
    }

    public int evaluate(String source, String pattern, int startp) {
        if (null == source || null == pattern){
            return 0;
        }
        Pattern r = Pattern.compile(pattern);
        int ret = -1;
        if (startp < source.length()){
            Matcher m = r.matcher(source.substring(startp));
            int count = 0;


            if (m.find()) {
                ret = m.start();
            }
        }
        return ret;
    }

    public int evaluate(String source, String pattern, int startp, int nth_occurrence) {
        if (null == source || null == pattern){
            return 0;
        }
        Pattern r = Pattern.compile(pattern);

        if (startp > source.length()){
            return -1;
        }

        Matcher m = r.matcher(source.substring(startp));
        int count = 0;
        int ret = -1;

        while (m.find()) {
            count++;
            if (count == nth_occurrence) {
                ret = m.start();
                break;
            }
        }

        return ret;
    }


    public int evaluate(String source, String pattern, int startp, int nth_occurrence, int return_option) {
        if (null == source || null == pattern){
            return 0;
        }
        Pattern r = Pattern.compile(pattern);

        if (startp > source.length()){
            return -1;
        }

        Matcher m = r.matcher(source.substring(startp));
        int count = 0;
        int ret = -1;

        while (m.find()) {
            count++;

            if (count == nth_occurrence) {
                if (return_option == 0) {
                    ret = m.start();
                } else {
                    ret = m.end();
                }
                break;
            }
        }

        return ret;
    }

}

